package com.sangeng.aspect;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.log.Log;
import com.sangeng.annotation.SystemLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.sangeng.annotation.SystemLog)")
    public void pt(){

    }

    @Around("pt()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取参数
        Object proceed = null;
        try {
            handleBefore(joinPoint);
            proceed = joinPoint.proceed();
            handleAfter(proceed);
        } finally {
            log.info("==========End==========" + System.lineSeparator());
        }
        return proceed;
    }

    public void handleBefore(ProceedingJoinPoint joinPoint){
        // 获取Url等参数的请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 获取被增强方法上的注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = getSystemLog(joinPoint);
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            log.info("=======Start=======");
            // 打印请求 URL
            log.info("URL            : {}", request.getRequestURL());
            // 打印描述信息
            log.info("BusinessName   : {}", systemLog.businessName());
            // 打印 Http method
            log.info("HTTP Method    : {}", request.getMethod());
            // 打印调用 controller 的全路径以及执行方法
            log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), methodSignature.getName());
            // 打印请求的 IP
            log.info("IP             : {}:{}", request.getRemoteHost(), request.getRemotePort());
            // 打印请求入参
            log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
        }
        else {
            log.info("无法获取request对象");
        }
    }

    private SystemLog getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        SystemLog systemLog = methodSignature.getMethod().getAnnotation(SystemLog.class);
        return systemLog;
    }

    public void handleAfter(Object proceed){
        // 打印出参
        log.info("Response       : {}", JSON.toJSONString(proceed));
    }
}
